/*
 * @lc app=leetcode.cn id=463 lang=cpp
 *
 * [463] 岛屿的周长
 */

// @lc code=start
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
    int islandPerimeter(vector<vector<int>> &grid)
    {
        int ans = 0;
        int updown[] = {-1, 1, 0, 0};
        int leftright[] = {0, 0, -1, 1};
        for (int i = 0; i < grid.size(); i++)
        {
            for (int j = 0; j < grid[0].size(); j++)
            {
                if (grid[i][j])
                {
                    int tmp = 0;
                    for(int k = 0; k < 4; k++)
                    {
                        int newi = i + updown[k];
                        int newj = j + leftright[k];
                        if(newi >= 0 && newi < grid.size() && newj >=0 && newj < grid[0].size())
                        {
                            if(grid[newi][newj] == 0) tmp++;
                        }
                        else
                        {
                            tmp++;
                        }
                    }

                    ans += tmp;
                }
            }
        }
        return ans;
    }
};

// int main(int argc, char const *argv[])
// {
//     vector<vector<int>> grid = {{0, 1, 0, 0}, {1, 1, 1, 0}, {0, 1, 0, 0}, {1, 1, 0, 0}};
//     cout << Solution().islandPerimeter(grid) << endl;
//     return 0;
// }

// @lc code=end
